package com.webapp.controller;

import java.io.File;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.webapp.model.UploadModel;

/**
 * Servlet implementation class Upload
 */
public class Upload extends HttpServlet {
	private static final long serialVersionUID = 1L; 
	
	private static final String DESTINATION_DIR_PATH ="/files";
	private File destinationDir;
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Upload() {
        super();
        // TODO Auto-generated constructor stub
    }

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
		String realPath = getServletContext().getRealPath(DESTINATION_DIR_PATH);
		System.out.print(realPath);
		destinationDir = new File(realPath);
		if(!destinationDir.isDirectory()) {
			boolean createdestinationDir = new File(realPath).mkdir();
		}
 
	}
	
	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String send = "";
		
		DiskFileItemFactory  fileItemFactory = new DiskFileItemFactory();
		fileItemFactory.setSizeThreshold(3*1024*1024); // file size
		ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
		File theFile = null;
		List<String> fileDirectories = new ArrayList();
		try {
			List items = uploadHandler.parseRequest(request);
			Iterator itr = items.iterator();
			while(itr.hasNext()) {
				FileItem item = (FileItem) itr.next();
				if(item.isFormField()) {
					send = item.getFieldName();
				} else {
					System.out.print(item.getFieldName());
					System.out.print(item.getName());
					System.out.print(item.getContentType());
					System.out.print(item.getSize());
					theFile = new File(destinationDir,item.getName());
					item.write(theFile);
					fileDirectories.add(theFile.getAbsolutePath());
				}
			}
		}catch(FileUploadException ex) {
			log("Error encountered while parsing the request",ex);
		} catch(Exception ex) {
			log("Error encountered while uploading file",ex);
		}
 
		
		System.out.println("SENDDDDDDD" + send);
	
		UploadModel um = new UploadModel();
		boolean test = um.uploadAY((String) fileDirectories.get(0), (String) fileDirectories.get(1), send);
		if(test == true) {
			response.sendRedirect("upload.jsp?upload=true");
		} else {
			response.sendRedirect("upload.jsp?upload=false");
		}

	}
}
